package com.smartfast4j;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.smartfast4j.common.component.fileManager.util.RemotingUtil;
import com.smartfast4j.manager.common.filter.ChangeParameterFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import java.util.ArrayList;
import java.util.List;

/**
 * 注：为了避免扫描路径不一致，将启动类放在Root Package 即 com.smartfast4j
 */
@ServletComponentScan
@SpringBootApplication
@EnableTransactionManagement// 启注解事务管理，等同于xml配置方式的 <tx:annotation-driven />
//扫描dao层的mapper类
@MapperScan("com.smartfast4j.mapper")
public class ManagerApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(ManagerApplication.class);

    //文件上传临时存放目录
    @Value("${fileUpload.tempSavePath}")
    private String tempSavePath;

    @Bean//使用@Bean注入fastJsonHttpMessageConvert
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1.需要定义一个Convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
        //2.添加fastjson的配置信息，比如是否要格式化返回的json数据
        FastJsonConfig fastJsonConfig=new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteNullStringAsEmpty,//字符类型字段如果为null,输出为"",而非null
                SerializerFeature.WriteNullListAsEmpty,//List字段如果为null,输出为[],而非null
                SerializerFeature.DisableCircularReferenceDetect //避免循环引用
        );
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        //3.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        //处理中文乱码问题(不然出现中文乱码)
        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        HttpMessageConverter<?> converter=fastConverter;
        return new HttpMessageConverters(converter);
    }

  /*  @Bean
    public FileService createInstance(){
       // return FileServiceFactory.getDefualInstance();
        return FileServiceFactory.getInstance(FileServiceFactory.SFTP_INSTANCE);//使用SFTP上传
    }*/

    /**
     * 文件上传临时路径
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //设置一个临时目录，解决：java.io.IOException: The temporary upload location [/tmp/tomcat.3541620039171925702.8092/work/Tomcat/localhost/ROOT] is not valid问题
        if(RemotingUtil.isLinuxPlatform()){//如果是Linux平台
            factory.setLocation(tempSavePath);
        }
        return factory.createMultipartConfig();
    }

    /**
     * 创建一个Filter bean
     * @return
     */
    @Bean
    public Filter changeParameterFilter() {
        return new ChangeParameterFilter();
    }

    /**
     * 配置过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(changeParameterFilter());
        registration.addUrlPatterns("/*");
        registration.setDispatcherTypes(DispatcherType.REQUEST,DispatcherType.FORWARD);
        registration.setName("changeParameterFilter");
        registration.setOrder(Integer.MAX_VALUE);//spring boot 会按照order值的大小，从小到大的顺序来依次过滤。
        //再有一个过滤器的话，可以设置成 registration.setOrder(Integer.MAX_VALUE - 1)
        return registration;
    }

    public static void main(String[] args) {
        SpringApplication.run(ManagerApplication.class, args);
    }
}
